package jwt

import (
	"bc/util"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

func JWT() gin.HandlerFunc{
	return func(c *gin.Context){

		var code int
		var data interface{}
		code = 200

		token := c.Request.Header.Get("token")

		if token ==""{
			code = 500
		}else{
			claims,err := util.ParseToken(token)

			if err != nil{
				code = 500
			}
			if time.Now().Unix() > claims.ExpiresAt{
				code = 500
			}
			if claims != nil{
				c.Set("uid",claims.Uid)
				c.Set("username",claims.Username)
			}
		}

		if code != 200{
			c.JSON(http.StatusUnauthorized,gin.H{
				"code":code,
				"msg" :"token expired",
				"data":data,
			})

			c.Abort()
			return
		}
		c.Next()
	}
}
